//
//  KABillDetailHeader.swift
//  kano
//
//  Created by Frank on 2024/9/18.
//

import Foundation
import UIKit
import ActiveLabel

class KABillDetailHeader: UIView {
    lazy var var_cornerView: UIView = {
        let var_cornerView = UIView()
        var_cornerView.backgroundColor = .themeColor
        var_cornerView.layer.cornerRadius = kscale(16)
        var_cornerView.layer.masksToBounds = true
        var_cornerView.frame = CGRectMake(kscale(12), kscale(12), width-kscale(24), kscale(160))
        return var_cornerView
    }()
    
    public var monthPayLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 1
        label.font = UIFont.systemFont(ofSize: kscale(30), weight: .bold)
        label.textColor = .white
        label.text = ""
        return label
    }()
    
    lazy var var_tipLabel: UILabel = {
        let var_tipLabel = UILabel()
        var_tipLabel.font = UIFont.systemFont(ofSize: kscale(12), weight: .regular)
        var_tipLabel.textColor = .white
        var_tipLabel.textAlignment = .center
        var_tipLabel.text = ""
        return var_tipLabel
    }()
    
    lazy var var_repayBtn: UIButton = {
        let button = UIButton()
        button.setTitle("Repay now", for: .normal)
        button.setTitleColor(.themeColor, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: kscale(14), weight: .bold)
        button.backgroundColor = .white
        button.layer.cornerRadius = kscale(20)
        button.layer.masksToBounds = true
        //        var_nextBtn.addTarget(self, action: #selector(ka_nextBtnClick), for: .touchUpInside)
        return button
    }()
    
    lazy var var_expView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = kscale(16)
        view.layer.masksToBounds = true
        view.frame = CGRectMake(var_cornerView.left, var_cornerView.bottom + kscale(12), var_cornerView.width, kscale(96))
        view.isHidden = true
        return view
    }()
    
    lazy var var_expLabel: UILabel = {
        let label = ActiveLabel()
        let customType = ActiveType.custom(pattern: "online service")
        label.enabledTypes = [customType]
        label.text = "The latest expected arrival time is within 24 hours. The payment speed may be affected by various factors. Please be patient. If you have not received the payment for a long time, please consult our online service for more information"
        label.textColor = .black
        label.backgroundColor = .white
        label.numberOfLines = 0
        label.font = kFontSize(12)
        label.customColor[customType] = .themeColor
        label.frame = CGRectMake(kscale(12), kscale(12), var_expView.width - kscale(24), kscale(72))
        label.handleCustomTap(for: customType, handler: { [self] (customType) in
            KAFlutterManager.showFlutterVC(route: "/onlineService", parameter: ["mobile" : KAUserManager.shared.user.notificationMessage])
        })
        return label
    }()
    
    var model: KABillDetailModel? {
        didSet {
            updateUI()
        }
    }
    
    func billDetailAmount() -> Double {
        guard let model = model else { return 0}
        
        switch (model.loanCondition) {
        case 0: fallthrough // 借款失败
        case 2: fallthrough// 还款失败
        case 3: fallthrough// 打款中
        case 8: fallthrough// 借款成功，等待打款
        case 9: // 审核中
            return model.overdueStatus
        case 1: // 已还款
            return model.businessProcessType
        case 4: fallthrough// 待还款
        case 5: // 已逾期
            return model.tadpoleLoanIndicator ? model.remainingLoanBalance : model.registrationConfirmation
        default:
            return 0
        }
    }
    
    private func updateUI() {
        guard let model = model else { return }
        
        if [3,8,9].contains(model.loanCondition) {
            var_expView.isHidden = false
            self.height = kscale(304)
        } else {
            var_expView.isHidden = true
            self.height = kscale(184)
        }
        
        
        monthPayLabel.text = "₦" + "\(billDetailAmount().separatorString())"
        
        switch (model.loanCondition) {
        case 0: // 借款失败
            var_tipLabel.text = "Loan Failed"
        case 1: // 已还款
            var_tipLabel.text = "Settled"
        case 2: // 还款失败
            var_tipLabel.text = "Repayment Failed"
        case 8: fallthrough // 借款成功，等待打款
        case 9: fallthrough // 审核中
        case 3: // 打款中
            var_tipLabel.text = "Application Amount"
        case 4: fallthrough // 待还款
        case 5: // 已逾期
            overDue(model: model)
        default:
            var_tipLabel.text = ""
        }
        
        //整体背景色
        //0：借款失败 红色
        //逾期红色。判断大小额是否逾期。大额，看分期有没有逾期；小额和蝌蚪贷看外层数据有没有逾期。
        //其他都是蓝色.判断当天到期并且未还款->黄色
        if model.loanCondition == 0 {
            var_cornerView.backgroundColor = .colorFF3644
        } else if model.ka_hasOverDueBill() {
            var_cornerView.backgroundColor = .colorFF3644
        } else {
            if model.ka_isDueTodayUnpay() {
                var_cornerView.backgroundColor = .colorFF8921
            } else {
                var_cornerView.backgroundColor = .themeColor
            }
        }
        
        //按钮文案
        if model.loanCondition == 4 || model.loanCondition == 5 {
            var_repayBtn.setTitle("Repay now", for: .normal)
        }
        else if [3,8,9].contains(model.loanCondition) {
            var_repayBtn.setTitle("Payment in progress", for: .normal)
        }
        else {
            var_repayBtn.setTitle("Back bill", for: .normal)
        }
        
        //按钮颜色
        //逾期 
        if model.ka_hasOverDueBill() {
            var_repayBtn.setTitleColor(.red, for: .normal)
            var_repayBtn.backgroundColor = .white
        } else if model.ka_isDueTodayUnpay() {
            var_repayBtn.setTitleColor(.colorFF8921, for: .normal)
            var_repayBtn.backgroundColor = .white
        } else {
            var_repayBtn.setTitleColor(.themeColor, for: .normal)
            var_repayBtn.backgroundColor = .white
        }
    }
    
    func overDue(model: KABillDetailModel) {
        //大额
        if model.secondaryLoanTotal > 0 && !model.tadpoleLoanIndicator {
            var subLoanModel = KABillDetailSubLoans()
            guard let subLoans = model.transactionUserType else { return }
            for subLoan in subLoans {
                if subLoan.emailProvider != 3 {
                    subLoanModel = subLoan
                    break
                }
            }
            if model.operationalStatus == 1 || model.operationalStatus == 4 {
                update(overDueDays: subLoanModel.overdueDuration)
            }
        }
        //蝌蚪贷、小额
        else {
            if model.operationalStatus == 1 || model.operationalStatus == 4 {
                update(overDueDays: model.overdueDuration)
            }
        }
    }
    
    func update(overDueDays: Int) {
        if overDueDays >= -3 &&  overDueDays < -1 {
            var_tipLabel.isHidden = false
            var_tipLabel.text = "due in \(abs(overDueDays)) day"
            var_tipLabel.textColor = .colorFF8921
            var_tipLabel.backgroundColor = .colorFFE9D5
            var_cornerView.backgroundColor = .colorFFE9D5
        }
        else if overDueDays == -1 {
            var_tipLabel.isHidden = false
            var_tipLabel.text = "due Tomorrow"
            var_tipLabel.textColor = .colorFF8921
            var_tipLabel.backgroundColor = .colorFFE9D5
            var_cornerView.backgroundColor = .colorFFE9D5
        }
        else if overDueDays == 0 {
            var_tipLabel.isHidden = false
            var_tipLabel.text = "due Today"
            var_tipLabel.textColor = .colorFF8921
            var_tipLabel.backgroundColor = .colorFFE9D5
            var_cornerView.backgroundColor = .colorFFE9D5
        }
        //已逾期
        else if overDueDays > 0 {
            var_tipLabel.isHidden = false
            var_tipLabel.text = "overdue \(abs(overDueDays)) day"
            var_tipLabel.textColor = .white
            var_tipLabel.backgroundColor = .colorFF3644
            var_cornerView.backgroundColor = .colorFF3644
        } else {
            var_tipLabel.isHidden = true
            var_cornerView.backgroundColor = .themeColor
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        ka_setUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension KABillDetailHeader {
    
    
    func ka_setUI() {
        backgroundColor = .colorF4F4FD
        addSubview(var_cornerView)
        var_cornerView.addSubview(monthPayLabel)
        var_cornerView.addSubview(var_tipLabel)
        var_cornerView.addSubview(var_repayBtn)
        addSubview(var_expView)
        var_expView.addSubview(var_expLabel)

        monthPayLabel.snp.makeConstraints { make in
            make.centerX.equalTo(var_cornerView)
            make.top.equalTo(kscale(28))
        }
        var_tipLabel.snp.makeConstraints { make in
            make.centerX.equalTo(var_cornerView)
            make.top.equalTo(monthPayLabel.snp.bottom).offset(kscale(8))
        }
        var_repayBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSizeMake(kscale(228), kscale(40)))
            make.centerX.equalTo(var_cornerView)
            make.top.equalTo(var_tipLabel.snp.bottom).offset(kscale(16))
        }
    }
}
